#include "SequenceItemDelegate.h"
#include "SequenceItemEditor.h"
#include "sequenceitem.h"

#include <QPainter>

SequenceItemDelegate::SequenceItemDelegate( QAbstractItemModel *lightModel,
                                            QAbstractItemModel *mediaModel, QObject *parent) :
   QStyledItemDelegate(parent),
   m_mediaModel(mediaModel),
   m_lightModel(lightModel)
{
}


QWidget *SequenceItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &,
                                            const QModelIndex &) const
{
   Q_ASSERT( (m_mediaModel != NULL) && (m_lightModel != NULL));

   SequenceItemEditor *editor = new SequenceItemEditor( m_mediaModel, m_lightModel, parent);
   editor->setWindowFlags( Qt::Popup);

   return editor;
}

void SequenceItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
   SequenceItemEditor * sequenceEditor = dynamic_cast<SequenceItemEditor *>(editor);
   const SequenceItem * itemData = index.data( Qt::EditRole).value<const SequenceItem *>();

   sequenceEditor->setNextItemIndex( itemData->indexOfNext());
   sequenceEditor->setDelayFromPrevious( itemData->delayMs());
   sequenceEditor->setEventType( itemData->type());
   sequenceEditor->setTargetLabel( itemData->label());
}

void SequenceItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                        const QModelIndex & index) const
{
   SequenceItemEditor * sequenceEditor = dynamic_cast<SequenceItemEditor *>(editor);
   SequenceItem temporary( sequenceEditor->delayFromPreviousMs(),
                           sequenceEditor->targetLabel(),
                           sequenceEditor->eventType(),
                           sequenceEditor->nextItemIndex());

   /* data for 'temporary' are copied at index row */
   model->setData( index, QVariant::fromValue<const SequenceItem *>(&temporary) , Qt::EditRole);
}

void SequenceItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
                                                const QModelIndex &) const
{
   /* only needed for pop-up window */
   QPoint containerTopLeft = editor->parentWidget()->mapToGlobal( QPoint( 0, 0) );
   QRect editorRect = option.rect.translated( containerTopLeft );
   editor->setGeometry( editorRect );
}

